package com.wzy.service.remind;

import com.wzy.common.base.redis.RedisUtil;
import com.wzy.common.base.result.R;
import com.wzy.common.base.sms.AliyunSmsSend;
import com.wzy.service.feign.UserArticleService;
import com.wzy.service.feign.UserInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/4/15 10:45
 * 4
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class StaticScheduleTask {
    @Autowired
    UserArticleService userArticleService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserInformationService userInformationService;

    //3.添加定时任务
    @Scheduled(cron = "0/10 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        // 获取用户文章表格中所有需要执行的任务
        R nextTimeArticle = userArticleService.getNextTimeArticle();
        Map<String, Object> data = nextTimeArticle.getData();
        //System.out.println(data);
        List<Map<String, String>> articles = (List<Map<String, String>>)data.get("articles");
        articles.forEach(t -> {
            String nextTime = t.get("nextTime");
            String id = t.get("id");
            String uid = t.get("uid");
            // 根据uid查到phone和name
            R informationByUId = userInformationService.getInformationByUId(uid);
            Map<String, String> user = (Map<String,String> )informationByUId.getData().get("user");
            String phone = user.get("phone");
            String name = user.get("nickname");
            if (nextTime != null  && redisUtil.get(id + "_" + nextTime) == null) {
                // 短信提醒
                nextTime = nextTime.substring(11,19);
                boolean b = AliyunSmsSend.sendMessage(name, nextTime, phone);
                System.out.println(b);
                // 插入redis
                redisUtil.set(id + "_" + nextTime, "1");
            }
        });
        System.out.println(articles);
    }

}